"""
评分系统 - Django Admin 管理界面
"""
from django.contrib import admin
from django.utils.html import format_html
from django.db.models import Count, Avg, Sum
from django.urls import reverse
from django.utils.safestring import mark_safe

from .models import (
    GradingStandard, GradeSheet, Grade, GradeComponent,
    GradeAppeal, GradeStatistics
)


class GradeLevelInline(admin.TabularInline):
    """评分等级内联"""
    model = GradeComponent
    extra = 0
    fields = ['name', 'weight', 'score', 'max_score', 'notes']


@admin.register(GradingStandard)
class GradingStandardAdmin(admin.ModelAdmin):
    """评分标准管理"""
    list_display = [
        'name', 'scope', 'full_score', 'passing_score',
        'is_default', 'is_active', 'creator', 'created_at'
    ]
    list_filter = [
        'scope', 'is_default', 'is_active', 'created_at'
    ]
    search_fields = ['name', 'description', 'creator__username', 'creator__real_name']
    readonly_fields = [
        'id', 'creator', 'created_at', 'updated_at'
    ]

    fieldsets = (
        ('基本信息', {
            'fields': ('name', 'description', 'scope')
        }),
        ('评分设置', {
            'fields': ('full_score', 'passing_score', 'is_default', 'is_active')
        }),
        ('等级设置', {
            'fields': ('grade_levels',),
            'description': '格式: {"A": {"min": 90, "max": 100}, "B": {"min": 80, "max": 89}}'
        }),
        ('系统信息', {
            'fields': ('creator', 'created_at', 'updated_at'),
            'classes': ('collapse',)
        })
    )

    def get_queryset(self, request):
        return super().get_queryset(request).select_related('creator')

    def save_model(self, request, obj, form, change):
        if not change:  # 新建时设置创建者
            obj.creator = request.user
        super().save_model(request, obj, form, change)


class GradeInline(admin.TabularInline):
    """成绩内联"""
    model = Grade
    extra = 0
    readonly_fields = [
        'student_info', 'exam_session_info', 'raw_score',
        'grade_level', 'is_passed'
    ]
    fields = [
        'student', 'final_score', 'comments', 'student_info',
        'exam_session_info', 'raw_score', 'grade_level',
        'is_passed'
    ]

    def student_info(self, obj):
        """学生信息"""
        if obj.student:
            return f"{obj.student.real_name} ({obj.student.username})"
        return "-"
    student_info.short_description = '学生'

    def exam_session_info(self, obj):
        """考试场次信息"""
        if obj.exam_session:
            return f"{obj.exam_session.examination.title}"
        return "-"
    exam_session_info.short_description = '考试'


@admin.register(GradeSheet)
class GradeSheetAdmin(admin.ModelAdmin):
    """成绩单管理"""
    list_display = [
        'title', 'examination', 'status', 'grades_count',
        'average_score', 'pass_rate', 'creator', 'created_at'
    ]
    list_filter = [
        'status', 'examination', 'grading_standard', 'created_at'
    ]
    search_fields = [
        'title', 'description', 'creator__username',
        'creator__real_name', 'examination__title'
    ]
    readonly_fields = [
        'id', 'grades_count', 'average_score', 'pass_rate',
        'creator', 'created_at', 'updated_at'
    ]
    inlines = [GradeInline]
    filter_horizontal = []

    fieldsets = (
        ('基本信息', {
            'fields': ('title', 'description', 'status')
        }),
        ('关联信息', {
            'fields': ('examination', 'course', 'grading_standard')
        }),
        ('审核信息', {
            'fields': ('reviewer', 'reviewed_at', 'review_notes'),
            'classes': ('collapse',)
        }),
        ('统计信息', {
            'fields': ('statistics',),
            'classes': ('collapse',)
        }),
        ('系统信息', {
            'fields': ('creator', 'created_at', 'updated_at'),
            'classes': ('collapse',)
        })
    )

    def grades_count(self, obj):
        """成绩数量"""
        count = obj.grades.count()
        return f"{count} 条"
    grades_count.short_description = '成绩数量'

    def average_score(self, obj):
        """平均分"""
        if obj.statistics and obj.statistics.get('average_score'):
            return f"{obj.statistics['average_score']:.2f}"
        return "-"
    average_score.short_description = '平均分'

    def pass_rate(self, obj):
        """及格率"""
        if obj.statistics and obj.statistics.get('pass_rate'):
            rate = obj.statistics['pass_rate']
            color = 'green' if rate >= 60 else 'red'
            return format_html(
                '<span style="color: {};">{:.1f}%</span>',
                color, rate
            )
        return "-"
    pass_rate.short_description = '及格率'

    def get_queryset(self, request):
        return super().get_queryset(request).select_related(
            'creator', 'reviewer', 'examination', 'course', 'grading_standard'
        ).prefetch_related('grades')

    def save_model(self, request, obj, form, change):
        if not change:  # 新建时设置创建者
            obj.creator = request.user
        super().save_model(request, obj, form, change)

    def get_readonly_fields(self, request, obj=None):
        if obj:  # 编辑已存在对象时
            readonly = list(self.readonly_fields)
            if obj.status == 'published':
                readonly.extend(['examination', 'grading_standard'])
            return readonly
        return self.readonly_fields

    def change_view(self, request, object_id=None, form_url='', extra_context=None):
        """自定义详情视图"""
        extra_context = extra_context or {}
        if object_id:
            try:
                grade_sheet = GradeSheet.objects.get(id=object_id)
                extra_context['show_grades_detail'] = True
                extra_context['grades_summary'] = {
                    'total': grade_sheet.grades.count(),
                    'passed': grade_sheet.grades.filter(is_passed=True).count(),
                    'failed': grade_sheet.grades.filter(is_passed=False).count(),
                }
            except GradeSheet.DoesNotExist:
                pass
        return super().change_view(request, object_id, form_url, extra_context)


@admin.register(Grade)
class GradeAdmin(admin.ModelAdmin):
    """成绩管理"""
    list_display = [
        'student_info', 'grade_sheet_title', 'final_score',
        'grade_level', 'is_passed'
    ]
    list_filter = [
        'grade_level', 'is_passed', 'grade_sheet__status',
        'grade_sheet__examination', 'created_at'
    ]
    search_fields = [
        'student__username', 'student__real_name',
        'grade_sheet__title', 'comments'
    ]
    readonly_fields = [
        'id', 'student', 'grade_sheet', 'examination',
        'grade_level', 'is_passed', 'created_at', 'updated_at'
    ]

    fieldsets = (
        ('基本信息', {
            'fields': ('student', 'grade_sheet', 'examination')
        }),
        ('成绩信息', {
            'fields': ('raw_score', 'final_score', 'grade_level', 'is_passed')
        }),
        ('备注信息', {
            'fields': ('comments',)
        }),
        ('调整记录', {
            'fields': ('adjustment_reason', 'adjusted_by', 'adjusted_at'),
            'classes': ('collapse',)
        }),
        ('系统信息', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        })
    )

    def student_info(self, obj):
        """学生信息"""
        if obj.student:
            return f"{obj.student.real_name} ({obj.student.username})"
        return "-"
    student_info.short_description = '学生'

    def grade_sheet_title(self, obj):
        """成绩单标题"""
        return obj.grade_sheet.title
    grade_sheet_title.short_description = '成绩单'

    def get_queryset(self, request):
        return super().get_queryset(request).select_related(
            'student', 'grade_sheet', 'exam_session', 'adjusted_by'
        )


class GradeComponentInline(admin.TabularInline):
    """成绩组件内联"""
    model = GradeComponent
    extra = 1
    fields = ['name', 'weight', 'score', 'max_score', 'notes']


@admin.register(GradeComponent)
class GradeComponentAdmin(admin.ModelAdmin):
    """成绩组件管理"""
    list_display = [
        'name', 'grade_info', 'score', 'max_score', 'weight', 'percentage'
    ]
    list_filter = ['name', 'created_at']
    search_fields = ['name', 'grade__student__real_name', 'notes']

    def grade_info(self, obj):
        """成绩信息"""
        if obj.grade:
            return f"{obj.grade.student.real_name} - {obj.grade.final_score}"
        return "-"
    grade_info.short_description = '考试成绩'

    def percentage(self, obj):
        """百分比"""
        if obj.max_score and obj.max_score > 0:
            pct = (obj.score or 0) / obj.max_score * 100
            return f"{pct:.1f}%"
        return "-"
    percentage.short_description = '得分率'

    def get_queryset(self, request):
        return super().get_queryset(request).select_related('grade', 'grade__student')


@admin.register(GradeAppeal)
class GradeAppealAdmin(admin.ModelAdmin):
    """成绩申诉管理"""
    list_display = [
        'student_info', 'grade_info', 'appeal_type',
        'status', 'expected_score', 'processed_by', 'created_at'
    ]
    list_filter = [
        'appeal_type', 'status', 'needs_regrading', 'created_at', 'processed_at'
    ]
    search_fields = [
        'student__username', 'student__real_name',
        'grade__student__real_name', 'reason', 'result'
    ]
    readonly_fields = [
        'id', 'student', 'grade', 'created_at', 'updated_at'
    ]

    fieldsets = (
        ('基本信息', {
            'fields': ('student', 'grade', 'appeal_type', 'status')
        }),
        ('申诉内容', {
            'fields': ('reason', 'expected_score')
        }),
        ('处理结果', {
            'fields': ('processed_by', 'processed_at', 'result', 'needs_regrading')
        }),
        ('系统信息', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        })
    )

    def student_info(self, obj):
        """学生信息"""
        if obj.student:
            return f"{obj.student.real_name} ({obj.student.username})"
        return "-"
    student_info.short_description = '申诉学生'

    def grade_info(self, obj):
        """成绩信息"""
        if obj.grade:
            return f"{obj.grade.final_score}分 - {obj.grade.grade_level}"
        return "-"
    grade_info.short_description = '考试成绩'

    def get_queryset(self, request):
        return super().get_queryset(request).select_related(
            'student', 'grade', 'processed_by'
        )

    def save_model(self, request, obj, form, change):
        if not change:  # 新建申诉时自动设置学生
            if obj.grade:
                obj.student = obj.grade.student
        super().save_model(request, obj, form, change)


@admin.register(GradeStatistics)
class GradeStatisticsAdmin(admin.ModelAdmin):
    """成绩统计管理"""
    list_display = [
        'title', 'examination', 'total_students',
        'average_score', 'pass_rate', 'creator', 'created_at'
    ]
    list_filter = [
        'examination', 'start_date', 'end_date', 'created_at'
    ]
    search_fields = [
        'examination__title',
        'creator__username', 'creator__real_name'
    ]
    readonly_fields = [
        'id', 'total_students', 'average_score', 'pass_rate',
        'creator', 'created_at', 'updated_at'
    ]

    fieldsets = (
        ('基本信息', {
            'fields': ('examination', 'grade_sheet')
        }),
        ('时间范围', {
            'fields': ('start_date', 'end_date')
        }),
        ('统计数据', {
            'fields': (
                'total_students', 'average_score', 'median_score',
                'std_deviation', 'variance'
            )
        }),
        ('分布数据', {
            'fields': ('score_distribution', 'grade_distribution', 'class_comparison'),
            'classes': ('collapse',)
        }),
        ('系统信息', {
            'fields': ('creator', 'created_at', 'updated_at'),
            'classes': ('collapse',)
        })
    )

    def title(self, obj):
        """标题"""
        if obj.examination:
            return f"{obj.examination.title} - 成绩统计"
        elif obj.course:
            return f"{obj.course.name} - 成绩统计"
        return "成绩统计数据"
    title.short_description = '标题'

    def pass_rate(self, obj):
        """及格率"""
        if obj.grade_distribution:
            passed = obj.grade_distribution.get('passed', 0)
            total = obj.total_students
            if total > 0:
                rate = passed / total * 100
                return f"{rate:.1f}%"
        return "-"
    pass_rate.short_description = '及格率'

    def get_queryset(self, request):
        return super().get_queryset(request).select_related(
            'creator', 'examination', 'course', 'grade_sheet'
        )

    def save_model(self, request, obj, form, change):
        if not change:  # 新建时设置创建者
            obj.creator = request.user
        super().save_model(request, obj, form, change)


# 自定义Admin站点配置
admin.site.site_header = 'AI-SOES 智能教务管理系统'
admin.site.site_title = 'AI-SOES 评分系统'
admin.site.index_title = '欢迎使用智能教务管理平台 - 评分系统管理'